package com.servlet;


import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author zxl
 * @create :2022/9/28
 */



//用户登录的处理器
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理登录的功能
       //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //2.获取请求的参数  String
        String username = request.getParameter("username");//用户
        System.out.println("username = " + username);
        String password = request.getParameter("password");//密码
         String remember=request.getParameter( "remember");//复选框

        //3.将参数封装为操作对象 user


        //4.使用对象调用Service方法进行操作
        User user = userService.login( new User(username,password));



        //5.判断结果并执行相关操作
        if(user != null){
            //登录成功
             //勾选
            if ("1".equals(remember)) {
             username = URLEncoder.encode(username, "UTF-8");

                Cookie cookie1=new Cookie("username",username);
                Cookie cookie2=new Cookie("password",password);
                //记住时间7天
                cookie1.setMaxAge(60*60*24*7);
                cookie2.setMaxAge(60*60*24*7);
                //提交给服务器
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            //没有勾
//            request.getSession().setAttribute("LOGIN_USER",user);
            request.getSession().setAttribute("user",user);
            response.sendRedirect(request.getContextPath()+"/student.jsp");

        }else{
            //登录失败
          request.setAttribute("msg","用户或是密码错误");
          //转发
          request.getRequestDispatcher("/login.jsp").forward(request,response);
        }


    }
}
